package com.android.RssReader;


import android.app.ActivityGroup;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;

import com.android.RssReader.Screen.IScreen;
import com.android.RssReader.Screen.IScreen.SCREEN_TYPE;
import com.android.RssReader.Screen.ScreenHome;
import com.android.RssReader.Screen.ScreenLogin;
import com.android.RssReader.Service.ScreenService;
import com.android.RssReader.Service.ServiceManager;

public class Main extends ActivityGroup {
	private final Handler handler;
	private final ScreenService screenService;
	
	
	 public Main()
	    {
	    	this.handler = new Handler();
	    	screenService = ServiceManager.getScreenservice();
	    }

	 
	 @Override
	public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	        ServiceManager.setMainActivity(this);
	        if (ServiceManager.isStarted()) {
				screenService.show(ScreenHome.class);
			} else {
				if (!ServiceManager.start()) {
					ServiceManager.exit();
					return;
				}
				 screenService.show(ScreenLogin.class, true);
			}
	        
	 }
	 
	 public void exit(){
			this.handler.post(new Runnable() {
				@Override
				public void run() {
					if (!ServiceManager.stop()) {
						RssReaderApplication.LogD(Main.class, "Failed to stop services");
					}				
					Main.this.finish();
				}
			});
		}
	 
		@Override
	    public boolean onKeyDown(int keyCode, KeyEvent event) {
			IScreen current = this.screenService.getCurrentScreen();
			if(current != null){
				 if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 && current.getType() != SCREEN_TYPE.SCREEN_HOME_T) {
					this.screenService.back();
					return true;
				} else if(keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0){
					if(!current.haveMenu()){
						return true;
					}
					else{
						return current.onKeyDown(keyCode, event);
					}
				}
			}
			return super.onKeyDown(keyCode, event);
		}
		
}
